package com.xhwl.data.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhwl.common.enums.OrganizationTypeEnum;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.Organization;
import com.xhwl.common.pojo.cent.sdata.OrganizationType;
import com.xhwl.common.pojo.cent.sdata.SpaceFunctionType;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.common.utils.StringUtils;
import com.xhwl.data.service.IOrganizationService;
import com.xhwl.data.service.IOrganizationTypeService;
import com.xhwl.data.service.ISpaceFunctionTypeService;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * @Author: luyi
 * @Description: 空间实体 单元
 * @Date: Create in 14:58 2021/5/31
 */
@RestController
public class UnitController {


    @Autowired
    private IOrganizationService organizationService;

    private static SecureRandom random = new SecureRandom();

    @Autowired
    private ISpaceFunctionTypeService spaceFunctionTypeService;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    @RequestMapping(value = "/unit/insert")
    public ResultJson insert(@RequestBody Organization organization) {

        if (StringUtils.isEmpty(organization.getName())) {
            return ResultJson.fail("名称为空");
        }
        if (StringUtils.isEmpty(organization.getName()) || organization.getName().length() > 32) {
            return ResultJson.fail("名称输入错误");
        }
        if (org.apache.commons.lang3.StringUtils.isNotEmpty(organization.getCode()) && organization.getCode().length() > 36) {
            return ResultJson.fail("编码输入错误");
        }
        organization.setType(OrganizationTypeEnum.UNIT.id.intValue());
        Organization parent = organizationService.getById(organization.getParentId());
        organization.setLevel(parent.getLevel() + 1);
        if (null == parent) {
            return ResultJson.fail("上级不存在");
        }
        if (null == organization.getId()) {
            if (StringUtils.isEmpty(organization.getCode())) {
                StringBuilder rs = new StringBuilder();
                for (int i = 0; i < 8; i++) {
                    rs.append(random.nextInt(10));
                }
                organization.setCode("U" + rs);
            }

            organization.setIndustryId(parent.getIndustryId());
            organization.setEnterpriseId(parent.getEnterpriseId());
            organization.setProjectId(parent.getProjectId());
            return organizationService.create(organization);
        } else {
            return organizationService.update(organization);
        }
    }

    @RequestMapping(value = "/unit/batch-create")
    public ResultJson batchInsert(@RequestBody List<Organization> organizations) {
        if (CollectionUtils.isEmpty(organizations)) {
            return ResultJson.fail("参数错误");
        }
        long count = organizations.stream().map(Organization::getCode).distinct().count();
        if(organizations.size() > count){
            return ResultJson.fail("编码重复");
        }
        long nameCount = organizations.stream().map(Organization::getName).distinct().count();
        if(organizations.size() > nameCount){
            return ResultJson.fail("名称重复");
        }
        for (Organization organization : organizations) {
            if (StringUtils.isEmpty(organization.getName())) {
                return ResultJson.fail("请填写名称");
            }
            organization.setType(OrganizationTypeEnum.UNIT.id.intValue());
            if (StringUtils.isEmpty(organization.getCode())) {
                StringBuilder rs = new StringBuilder();
                for (int i = 0; i < 8; i++) {
                    rs.append(random.nextInt(10));
                }
                organization.setCode("U" + rs);
            }
        }
        Integer parentId = organizations.get(0).getParentId();
        Organization parent = organizationService.getById(parentId);
        if (null == parent) {
            return ResultJson.fail("上级不存在");
        }

        for (Organization organization : organizations) {
            organization.setIndustryId(parent.getIndustryId());
            organization.setEnterpriseId(parent.getEnterpriseId());
            organization.setProjectId(parent.getProjectId());
            organization.setLevel(parent.getLevel() + 1);
        }
        boolean b = organizationService.saveBatch(organizations);
        return b ? ResultJson.success() : ResultJson.fail("批量新增失败");
    }

    @RequestMapping(value = "/unit/delete")
    public ResultJson delete(Integer id) {
        return organizationService.delete(id, null);
    }

    @RequestMapping(value = "/unit/page")
    public ResultJson page(@RequestBody OrganizationQuery organizationQuery, Page page) {
        organizationQuery.withTypes(Arrays.asList(OrganizationTypeEnum.UNIT.id.intValue()));
        Page page1 = organizationService.page(organizationQuery, page);
        List<Organization> records = page1.getRecords();
        List<SpaceFunctionType> spaceFunctionTypes = this.listFunctionType();
        records.forEach(x -> processBean(x, spaceFunctionTypes,organizationQuery.getTypeId()));
        page1.setRecords(records);
        return ResultJson.success(page1);
    }

    /**
     * 详情
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/unit/detail")
    public ResultJson detail(Integer id, Integer orgId,Integer typeId) {
        if (null == id && null == orgId) {
            return ResultJson.fail("参数错误");
        }
        Organization organization = organizationService.getById(id == null ? orgId : id);
        if (null != organization && OrganizationTypeEnum.UNIT.id.intValue() == organization.getType()) {
            UnitDTO unitDTO = new UnitDTO();
            BeanUtils.copyProperties(organization, unitDTO);
            unitDTO.setOrganizationId(organization.getId());
            List<SpaceFunctionType> spaceFunctionTypes = this.listFunctionType();
            return ResultJson.success(processBean(unitDTO,spaceFunctionTypes,typeId));
        }
        return ResultJson.success();
    }

    @Data
    class UnitDTO extends Organization {

        private Integer organizationId;

    }

    private Organization processBean(Organization organization, List<SpaceFunctionType> spaceFunctionTypes,Integer typeId) {
        if (null != organization.getFunctionType()) {
            for (SpaceFunctionType spaceFunctionType : spaceFunctionTypes) {
                if (organization.getFunctionType().equals(spaceFunctionType.getId())) {
                    organization.setFunctionName(spaceFunctionType.getName());
                }
            }
        }
        dealJson (organization,typeId);
        return organization;
    }

    private List<SpaceFunctionType> listFunctionType() {
        return spaceFunctionTypeService.list(new QueryWrapper<SpaceFunctionType>()
                .eq("org_type", OrganizationTypeEnum.UNIT.getId()));
    }

    /**
     * 兼容历史数据
     */
    private void dealJson (Organization param, Integer typeId){
        if(typeId == null){
            return;
        }
        QueryWrapper<OrganizationType> organizationTypeQueryWrapper = new QueryWrapper<>();
        organizationTypeQueryWrapper.eq("id", typeId);
        OrganizationType organizationType = organizationTypeService.getOne(organizationTypeQueryWrapper);
        String source = organizationType.getSource();
        if(org.apache.commons.lang3.StringUtils.isEmpty(source)){
            return;
        }
        Map<String,Object> map = new HashMap<>();
        JSONObject sourceJson = JSON.parseObject(source);
        JSONArray fields = sourceJson.getJSONArray("fields");
        if(CollectionUtil.isNotEmpty(fields)) {
            for (int i = 0; i < fields.size(); i++) {
                JSONObject fieldJsonObject = fields.getJSONObject(i);
                fieldJsonObject.remove("__config__");
                String vModel = fieldJsonObject.getString("vModel");
                //兼容以前数据
                if ("name".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getName() != null ? param.getName() : "");
                    map.put("name",param.getName() != null ? param.getName() : "");
                } else if ("code".equals(vModel)) {
                    fields.getJSONObject(i).put("defaultValue",param.getCode() != null ? param.getCode() : "");
                    map.put("code",param.getCode() != null ? param.getCode() : "");
                } else if ("sortField".equals(vModel)){
                    fields.getJSONObject(i).put("defaultValue",param.getSortField() != null ? param.getSortField() : "");
                    map.put("sortField",param.getSortField() != null ? param.getSortField() : "");
                } else {
                    if(param.getExpand() != null) {
                        JSONObject jsonObject = JSON.parseObject(param.getExpand());
                        if(jsonObject.get(vModel) != null) {
                            fields.getJSONObject(i).put("defaultValue", jsonObject.get(vModel));
                            map.put(vModel,jsonObject.get(vModel));
                        }else{
                            map.put(vModel,"");
                        }
                    }else{
                        map.put(vModel,"");
                    }
                }
            }
        }
        param.setExpand(JSON.toJSONString(sourceJson));
        param.setFullData(JSON.toJSONString(map));
    }
}

